<?php
session_start(); // 启用Session
require_once __DIR__.'/../../utils/checkTokenUtils.php';
require_once __DIR__.'/../../utils/MysqlDBUtils.php';
use utils\MysqlDBUtils;

// 获取来源页面信息
$referer = $_SERVER['HTTP_REFERER'] ?? '';
// 从URL中获取category_id
$urlComponents = parse_url($referer);
parse_str($urlComponents['query'] ?? '', $queryParams);
$categoryId = isset($queryParams['category_id']) ? intval($queryParams['category_id']) : null;

// 仅允许POST请求
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    die("错误：仅支持POST请求");
}

// 初始化数据库连接
$dbUtil = new MysqlDBUtils();

// 获取并验证表单数据
$id = isset($_POST['id']) ? intval($_POST['id']) : 0;

// 验证必填字段
if (empty($id)) {
    http_response_code(400);
    die("必填字段（id）不能为空");
}

// 构建删除SQL
// 使用预处理语句防止SQL注入
$deleteSql = "DELETE FROM book WHERE id = $id";
$result = $dbUtil->prepareQuery($deleteSql);

if ($result !== false) {
    // 删除成功时存储提示信息到Session
    $_SESSION['success_message'] = '图书删除成功！';
} else {
    $_SESSION['error_message'] = '错误：数据库删除失败';
}

// 根据来源页面进行重定向
if (strpos($referer, 'BookCategory.php') !== false && $categoryId !== null) {
    $q = isset($_GET['q']) ? trim($_GET['q']) : '';
    $currentPage = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
    $perPage = isset($_GET['per_page']) ? intval($_GET['per_page']) : 8;
    header("Location: BookCategory.php?category_id=$categoryId&q=$q&page=$currentPage&per_page=$perPage");
} else {
    $q = isset($_GET['q']) ? trim($_GET['q']) : '';
    $currentPage = max(1, intval($_GET['page'] ?? 1));
    $perPage = max(1, min(intval($_GET['per_page'] ?? 8), 100));
    header("Location: Books.php?q=$q&page=$currentPage&per_page=$perPage");
}
exit;